#pragma once 
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>
#include"task.hpp"



struct threadInfo
{
    pthread_t tid;
    std::string name; 
};


const static int defaultnum = 5;

template<class T>
class ThreadPool
{
public:
    //构造函数
    ThreadPool(int num = defaultnum)
        :_threads(num)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_cond,nullptr);
    }
    //析构函数
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
    //加锁
    void lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    //解锁
    void unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    //等待
    void thread_sleep()
    {
        pthread_cond_wait(&_cond,&_mutex);
    }
    //唤醒
    void wake_up()
    {
        pthread_cond_signal(&_cond);
    }
    //判断任务队列
    bool is_queue_empty()
    {
        return _tasks.empty();
    }

    //获取进程id
    std::string GetThreadName(pthread_t tid)
    {
        for(auto& ti : _threads)
        {
            if(ti.tid == tid)
            {
                return ti.name;
            }
        }
    } 

    //线程并发
    static void* HeeaderTask(void* args)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        std::string threadnme = tp->GetThreadName(pthread_self());
        while(true)
        {
            
            tp->lock();
            while(tp->is_queue_empty())//while 避免错误唤醒
            {
                tp->thread_sleep();
            }
            T t = tp->pop();
            
            tp->unlock();
            t.run();
            cout << threadnme <<"run, "<< "result" << t.Getresult() <<endl;
        }
        return nullptr;
    }

    void start()
    {
        int num = _threads.size();
        for(int i = 1; i <= num;i++)
        {
            _threads[i-1].name = std::to_string(i);
            pthread_create(&(_threads[i-1].tid),nullptr,HeeaderTask,this);//this指针！！
        }
    }

    void push(const T& in)
    {
        lock();
        _tasks.push(in);
        wake_up();
        unlock();
    }

    T pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }


private:
std::vector<threadInfo> _threads;
std::queue<T> _tasks;

pthread_mutex_t _mutex;
pthread_cond_t _cond;
};

